/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package psd.semana1.aula.semaforo;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 *
 * @author nfsa
 */
public class ThreadLigacao extends Thread {

    private Socket socket;
    private Semaforo semaforo;
    private Scanner inputStream;
    private PrintWriter outputStream;
    
    public ThreadLigacao (Socket _socket, Semaforo _semaforo) {
        socket = _socket;
        semaforo = _semaforo;
    }

    @Override
    public void run() {
        try
        {
            inputStream = new Scanner(socket.getInputStream());
            outputStream = new PrintWriter(socket.getOutputStream());
            
            while (inputStream.hasNextLine())
            {
                String readString = inputStream.nextLine();

                char op = '*';
                int valor = 0;

                if (readString != null && readString.matches("[aA/+bB/-][0-9]+\r?\n?"))
                {
                    op = readString.charAt(0);
                    valor = Integer.parseInt(readString.substring(1));
                }
                
                switch (op)
                {
                    case '+':
                    case 'a':
                    case 'A':
                        semaforo.somar(valor);
                        break;
                    case '-':
                    case 'b':
                    case 'B':
                        semaforo.subtrair(valor);
                        break;
                    default:
                        break;
                }

                outputStream.println("Valor actual: " + semaforo.valor());
                outputStream.flush();
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
